import { NbcbService } from '@/core/nbcb.service';
import { UopService } from '@/core/uop.service';
import { Public } from '@/decorators';
import { UopPaymentTypeEnum } from '@/enums';
import { getCode, getNanoid, halt, ok } from '@/utils';
import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { BaseController } from './base.controller';

@Controller('uop')
export class UopController extends BaseController {
  constructor(
    private readonly uopService: UopService,
    private readonly nbcbService: NbcbService,
  ) {
    super();
  }

  @Get('access-token')
  async getAccessToken() {
    return ok(await this.uopService.getToken());
  }

  @Post('order')
  async getOrder(
    @Body('no') no: string,
    @Body('type') type: UopPaymentTypeEnum,
  ) {
    return ok(await this.uopService.query(no, type));
  }

  @Public()
  @Get('test/query')
  async test(@Query('serialNo') serialNo: string) {
    return ok(
      await this.nbcbService.querySingleTransferResult({
        serialNo,
      }),
    );
  }

  @Public()
  @Get('test/refund')
  async testRefund(@Query('date') date: string) {
    const res = await this.nbcbService.queryRefund({ date });

    if (!res || res?.Data?.retCode !== '0000') {
      return halt(`退汇查询失败: ${res?.Data?.retMsg ?? '未知错误'}`);
    }

    const refundDtls = res?.Data?.refundDtls ?? [];

    for (let o of refundDtls) {
      await this.prisma.refundBill.upsert({
        where: {
          refundCoreNo: o.refundCoreNo,
        },
        update: {
          ...o,
        },
        create: {
          ...o,
          createdAt: new Date(date),
        },
      });
    }

    return ok(res);
  }

  @Public()
  @Get('test/download')
  async testDownload(@Query('tradeType') tradeType: string = 'BANKNO') {
    return ok(await this.nbcbService.getGeneralDownloadUrl({ tradeType }));
  }
}
